﻿using Client.Framework.Event;
using Client.Framework.Message;
using Client.Model;
using SuperSocket.ClientEngine;
using System;
using System.Net;

namespace Client.Framework.Socket
{
    /// <summary>
    /// Author: Leil
    /// Description: 服务客户端
    /// CreateTime: 2020/5/12 10:05:59
    /// </summary>
    class ApplicationClient
    {
        public ViewUser CurrentLoginUser { get; set; }

        private static ApplicationClient instance;

        private ApplicationClient() { }

        /// <summary>
        /// 服务客户端
        /// </summary>
        public EasyClient Client { get; private set; }

        /// <summary>
        /// 获取客户端服务实例
        /// </summary>
        /// <returns>实例</returns>
        public static ApplicationClient Instance()
        {
            if (instance == null)
            {
                instance = new ApplicationClient();
            }
            return instance;
        }

        /// <summary>
        /// 初始化客户端
        /// </summary>
        public void InitClient()
        {
            Client = new EasyClient();
            Client.Initialize(new ProtobufReceiveFilter(), requestInfo =>
            {
                Received(requestInfo);
            });

            if (Client.ConnectAsync(new DnsEndPoint("127.0.0.1", 7777)).Result)
            {
                Console.WriteLine("Connect success!!!");
            }
        }


        /// <summary>
        /// 消息接收处理
        /// </summary>
        /// <param name="requestInfo"></param>
        public void Received(ProtobufPackageInfo requestInfo)
        {
            if (requestInfo != null)
            {
                MessageEventPublisher.TriggerEvent(requestInfo.Body);
                return;
            }
            Console.WriteLine("Message body is null");
        }

        /// <summary>
        /// 客户端消息发送
        /// </summary>
        /// <param name="message">消息体</param>
        public void Send(RequestBaseMessage message)
        {
            byte[] buffer = message.Encode();
            Client.Send(buffer);
        }

    }
}
